package com.karaoke.android.library.mvvm

import android.content.Context
import android.databinding.DataBindingUtil
import android.databinding.ViewDataBinding
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import universum.studios.android.fragment.BaseFragment
import kotlin.properties.Delegates

/**
 * Created by Administrator on 2016/12/1.
 */
abstract class MvvmFragment<out VM : FragmentViewModel> : BaseFragment()
{
    abstract val viewModel: VM
    protected var dataBinding: ViewDataBinding by Delegates.notNull()
    abstract val config: BindingConfig
    var title = ""
    private var firstLaunch = true

    protected open fun onInitLoad()
    {

    }


    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View?
    {
        dataBinding = DataBindingUtil.inflate(inflater, config.layoutId, container, false)
        dataBinding.setVariable(config.bindingVariable, viewModel)
        dataBinding.executePendingBindings()
        return dataBinding.root
    }


    override fun onViewCreated(view: View?, savedInstanceState: Bundle?)
    {
        super.onViewCreated(view, savedInstanceState)
        viewModel.onViewCreated(view, savedInstanceState)
        if (firstLaunch)
            onInitLoad()
    }

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        viewModel.onCreate(savedInstanceState)
    }

    override fun onAttach(context: Context?)
    {
        super.onAttach(context)
        viewModel.onAttach(context)
    }

    override fun onResume()
    {
        super.onResume()
        viewModel.onResume()
    }

    override fun onStart()
    {
        super.onStart()
        viewModel.onStart()
    }

    override fun onPause()
    {
        super.onPause()
        viewModel.onPause()
    }

    override fun onDestroy()
    {
        super.onDestroy()
        firstLaunch = false
        viewModel.onDestroy()
    }

    override fun onDetach()
    {
        super.onDetach()
        viewModel.onDetach()
    }

    override fun onDestroyView()
    {
        super.onDestroyView()
        firstLaunch = false
        viewModel.onDestroyView()
    }
}